import pandas as pd
from sqlalchemy.orm import Session
from typing import Dict
from app.service_quality.models.qos_http_request import QosHttpRequest
from common.utils import get_month_range


def http_reg_time_ratio_chart_handler(data_month, db: Session) -> Dict:
    result = QosHttpRequest.get_req_time_avg_aggregate(db, data_month)
    if not result:
        return {}
    df = pd.DataFrame(result)
    df_req_time_top_10 = df[:10].copy(deep=False)
    df_req_time_top_10['request'] = df_req_time_top_10.apply(lambda x: f"{x['domain_name']} {x['verb']} {x['url']}",
                                                             axis=1)
    avg_req_time_groups = pd.cut(df['avg_req_time'],
                                 bins=[0, 1, 2, 3, max(df['avg_req_time'] + 1)],
                                 labels=["耗时 <= 1秒", "1秒 > 耗时 <= 2秒", "2秒 > 耗时 <= 3秒", "耗时 >= 3秒"],
                                 ordered=False)
    df = df.groupby(avg_req_time_groups)['avg_req_time'].count().to_frame('count')
    df.insert(0, 'avg_req_time', df.index)

    return {'req_time_agg': df.to_dict(orient="records"),
            'req_time_top10': df_req_time_top_10.to_dict(orient="records")}


def http_4xx_chart_handler(data_month, db: Session) -> Dict:
    result = QosHttpRequest.get_http_status_count_aggregate(db, data_month)

    print(result)
    if not result:
        return {}

    df = pd.DataFrame(result)
    df['percent'] = df.apply(
        lambda x: round(int(x['http_status_4xx']) / int(x['request_count']) * 100, 2), axis=1)
    df = df.sort_values(['percent'], ascending=[False])
    df_4xx_top_10 = df[:10].copy(deep=False)
    df_4xx_top_10['request'] = df_4xx_top_10.apply(lambda x: f"{x['domain_name']} {x['verb']} {x['url']}", axis=1)
    percent_4xx_groups = pd.cut(df['percent'],
                                bins=[-1, 0, 1, 5, 100],
                                labels=["百分率 == 0%", "百分率 <= 1%", "1% > 百分率 <= 5%", "百分率 > 5%"],
                                ordered=False)
    req_4xx_dist = df.groupby(percent_4xx_groups)['percent'].count().to_frame('count')

    req_4xx_dist.insert(0, 'percent', req_4xx_dist.index)
    return {'req_4xx_dist': req_4xx_dist.to_dict(orient="records"),
            '4xx_top10': df_4xx_top_10.to_dict(orient="records")}


def http_5xx_chart_handler(data_month, db: Session):
    result = QosHttpRequest.get_http_status_count_aggregate(db, data_month)
    if not result:
        return {}

    df = pd.DataFrame(result)
    df['percent'] = df.apply(
        lambda x: round(int(x['http_status_5xx']) / int(x['request_count']) * 100, 2), axis=1)
    df = df.sort_values(['percent'], ascending=[False])
    df_5xx_top_10 = df[:10].copy(deep=False)
    df_5xx_top_10['request'] = df_5xx_top_10.apply(lambda x: f"{x['domain_name']} {x['verb']} {x['url']}", axis=1)
    percent_5xx_groups = pd.cut(df['percent'],
                                bins=[-1, 0, 1, 5, 100],
                                labels=["百分率 == 0%", "百分率 <= 1%", "1% > 百分率 <= 5%", "百分率 > 5%"],
                                ordered=False)
    req_5xx_dist = df.groupby(percent_5xx_groups)['percent'].count().to_frame('count')

    req_5xx_dist.insert(0, 'percent', req_5xx_dist.index)
    return {'req_5xx_dist': req_5xx_dist.to_dict(orient="records"),
            '5xx_top10': df_5xx_top_10.to_dict(orient="records")}
